import axios from "axios";
import { defineStore } from "pinia";


axios.defaults.baseURL = "http://localhost:3000";

export const useDataStore = defineStore("data", {
    state: () => ({
        //后端请求数据
        data: [],
        // //帖子列表
        // postls: [],
        //活动列表
        actls: [],
        //活动详情
        act: {},
        //帖子详情
        post: {},
        //评论列表
        commentls: [],
        //用户信息
        user: {},
        //部落列表
        tribels: [],

        MvList: [],
        isPlaying: false,
        songName: '',
        length: 0,
        obj: {}
    }),
    actions: {
        // // 获取所有帖子(触底加载)
        // async getPost(page) {
        //     const { data: { ls } } = await axios.get("/getPost?page=" + page + "&limit=2");
        //     this.postls = this.postls.concat(ls)
        //     console.log('ls', ls)
        //     if (ls.length === 0) {
        //         console.log('No more posts to load.');
        //         return ;
        //     }
        // },


        // 获取单条帖子
        async getPostDetail(id) {
            const { data: { post } } = await axios.get(`/getPostDetail/?id=${id}`);
            //格式化时间----------------------
            // 创建Date对象
            const date = new Date(post.time);

            // 获取各个组成部分
            const month = date.getMonth() + 1; // 月份从0开始，所以加1
            const day = date.getDate();
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');

            // 格式化为所需格式：X月XX日 时:分
            const formattedTime = `${month}月${String(day).padStart(2, '0')}日 ${hours}:${minutes}`;
            post.time = formattedTime;
            // --------------------------------

            // 格式化评论时间 格式：xxxx年MM月dd日 HH:mm
            post.comments.forEach(item => {
                if (item.createdAt) {
                    const date = new Date(item.createdAt);

                    // 获取各个组成部分
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    const hours = String(date.getHours()).padStart(2, '0');
                    const minutes = String(date.getMinutes()).padStart(2, '0');
                    // 格式化为所需格式：xxxx年MM月dd日 HH:mm
                    item.createdAt = `${year}年${month}月${day}日 ${hours}:${minutes}`;
                }
            })

            this.post = post;
        },

        // 获取所有活动
        async getAct() {
            const { data: { ls } } = await axios.get("/getAct");
            this.actls = ls;
        },
        //获取单条活动
        async getActDetail(id) {
            const { data: { act } } = await axios.get(`/getActDetail/?id=${id}`);

            //格式化时间----------------------
            // 创建Date对象
            const date = new Date(act.time);

            // 获取各个组成部分
            const month = date.getMonth() + 1; // 月份从0开始，所以加1
            const day = date.getDate();
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');

            // 格式化为所需格式：X月XX日 时:分
            const formattedTime = `${month}月${String(day).padStart(2, '0')}日 ${hours}:${minutes}`;
            act.time = formattedTime;
            // --------------------------------

            this.act = act;
        },

        //发送评论
        async sendComment(id, content) {
            await axios.post(`/sendComment?id=${id}`, {
                content,
                avatar: localStorage.getItem('avatar') || './图片/tx2.jpg',
                name: localStorage.getItem('name') || '欢欢',
            })
        },

        //获取所有部落
        async getAllTribe() {
            let { data: { ls } } = await axios.get('/getTribe')
            this.tribels = ls
        },

        async getMvList(cid) {
            await axios.get(`http://localhost:3000/getMvList/?cid=${cid}`)
                .then(res => {
                    this.MvList = res.data.list
                    this.length = res.data.list.classList.length
                    console.log(res.data.list);
                    console.log(res.data.list.classList.length, '111');
                })
        },
        async start(name, cid) {
            console.log('start', name, cid);
            axios
                .get(`http://localhost:3000/updateState/?name=${name}&id=${cid}`)
                .then((res) => {
                    // console.log(res.data);
                    this.obj = res.data.obj
                });
        },
        async end(name, cid) {
            console.log('end', name, cid);
            axios
                .get(`http://localhost:3000/updateStateN/?name=${name}&id=${cid}`)
                .then((res) => {
                    // console.log(res.data,.);
                    this.obj = res.data.obj
                });
        },
        play() {
            // 播放音乐逻辑
            let url = JSON.parse(localStorage.getItem('data')).obj.link
            let audio = new Audio(url);
            audio.play()
        },
        pause() {
            // 暂停音乐逻辑
            let url = JSON.parse(localStorage.getItem('data')).obj.link
            let audio = new Audio(url);
            audio.pause()
        },
        // 其他方法...
    }
});

